<?php
namespace app\api\controller;

use app\common\model as M;

/**
 * 用户模块
 */
class User extends \app\api\ApiAuth
{
    public $model = '\app\common\model\User';
	
	public static function WhiteList()
	{
	    return ['logout'];
	}
	
    /**
     * 退出登录
     * @Author   FW
     * @DateTime 2024-03-13
     * @Email    123763712@qq.com
     * @return   [type]           [description]
     */
    public function logout ()
    {
        if ( $this->token ) {
			$this->model::clear_login($this->token);
		}
        return $this->returnSuccess();
    }

    /**
     * 用户地址列表
     * @Author   FW
     * @DateTime 2024-03-13
     * @Email    123763712@qq.com
     * @return   [type]           [description]
     */
    public function address()
    {
        return $this->returnSuccess(M\user\UserAddress::listByUid($this->uid));
    }

    /**
     * 获取微信小程序授权手机号
     * @Author   FW
     * @DateTime 2024-03-14
     * @Email    123763712@qq.com
     * @return   [type]           [description]
     */
    public function wechatPhonenumber()
    {
        $code    = $this->request->post('code');
        if ( empty($code) ) return $this->returnFail('code必传!');

        try {
            $res = \service\WechatMicroProgramService::getPhoneNumber($code);

            if ( isset($res['phone_info']) ) {
                return $this->returnSuccess($res['phone_info']);
            }

            if ( isset($res['errcode']) && isset($res['errmsg']) ) throw new \Exception($res['errmsg']);
        } catch (\Exception $e ) {
            return $this->returnFail($e->getMessage());
        }

        return $this->returnFail('获取失败，请稍后重试!');
    }

    /**
     * 保存用户信息
     * @Author   FW
     * @DateTime 2024-03-14
     * @Email    123763712@qq.com
     * @return   [type]           [description]
     */
    public function saveInfo()
    {
        $userInfo = $this->request->post();
        if ( empty($userInfo) ) return $this->returnFail('数据为空');

        $fromType = input('fromtype'); // edit / login

        M\User::startTrans();
        try {
            $mobile = $userInfo['mobile'] ?? '';
            $is_idcheck = $this->userInfo['is_idcheck'] ?? 0;

            ## 咱不得(dei,3声)看看这个手机号码之前是否已经存在？
            $birthday = '';
            if ( $fromType == 'login' ) {
                if ( $mobile ) {
                    $mobileUser = $this->model::where('mobile' , $mobile)->find();

                    if ( !empty($mobileUser) ) {
                        if ( $mobileUser->uid != $this->uid ) {
                            $deleteUser = $this->model::where('uid' , $this->uid)->find();
                            $mobileUser->openid  = $deleteUser->openid;
                            $mobileUser->unionid = $deleteUser->unionid;

                            ## 删除当前这个刚注册的用户
                            $res = $this->model::deleteUser($this->uid);
                            if ( $res !== true ) throw new Exception('操作失败【1000】');

                            $this->uid = $mobileUser->uid;
                            $this->userInfo = $mobileUser->toArray();
                        }
                    }
                }

                ## 检查是否有身份证号等实名数据并保存
                $realname = $userInfo['realname'] ?? '';
                $idnumber = $userInfo['idnumber'] ?? '';
                $address  = $userInfo['address'] ?? '';
                if ( !$realname || !$idnumber ) throw new Exception('首次注册登录须完善实名信息');

                $res = M\user\UserIdcard::saveOne([
                    'uid'       => $this->uid,
                    'realname'  => $realname,
                    'idnumber'  => $idnumber,
                    'address'   => $address,
                    'check_time'=> date('Y-m-d H:i:s')
                ]);
                if ( $res === false ) throw new \Exception('实名认证信息保存失败');

                $birthday = idnumber2birthday($idnumber);
                $is_idcheck = 1;
            }

            $user = new $this->model;
            $safeData = [
                'avatar'      => $userInfo['avatar'] ?? '',
                'nickname'    => $userInfo['nickname'] ?? '',
                'birthday'    => $userInfo['birthday'] ?? '',
                'mobile'      => $mobile,
                'tour_perfer' => $userInfo['tour_perfer'] ?? '',
                'tour_target' => $userInfo['tour_target'] ?? '',
                'is_idcheck'  => $is_idcheck,
                'birthday'    => $birthday,
            ];

            foreach ( $safeData as $k => $v ) {
                if ( empty($v) ) unset($safeData[$k]);
            }

            $res  = $user->allowField(true)->save($safeData, ['uid' => $this->uid]);

            if ( $res === false ) throw new \Exception('保存失败【1001】');

            ## 更新缓存中的用户信息
            $safeData['golds'] = $this->userInfo['golds'] ?? 0;
            $this->userInfo = array_merge($this->userInfo , $safeData);

            $this->userInfo = M\User::set_login($this->userInfo);

            M\User::commitTrans();
            return $this->returnSuccess($this->userInfo);
        } catch (\Exception $e ) {
            M\User::rollbackTrans();
            return $this->returnFail($e->getMessage());
        }

        M\User::rollbackTrans();
        return $this->returnFail('保存失败【10020097】');
    }

    /**
     * 登录记录
     * @Author   FW
     * @DateTime 2024-03-22
     * @Email    123763712@qq.com
     * @return   [type]           [description]
     */
    public function loginRecords()
    {
        $post = $this->request->post();
        if ( !empty($post) ) {
            $post['uid'] = $this->uid;
            $post['loginDay'] = date('Y-m-d');
            $post['loginTime'] = date('Y-m-d H:i:s');

            $record = M\UserLoginRecords::where(['uid'=>$post['uid'],'loginDay'=>$post['loginDay']])->count();
            if ( $record > 0 ) goto NOTHING;

            M\UserLoginRecords::startTrans();
            try {
                $res = (new M\UserLoginRecords)->allowField(true)->save($post);
                if ( $res === false ) throw new \Exception('Error 1001');

                $params['uid'] = $this->uid;
                \think\Hook::exec('app\common\behavior\LoginSuccess','run',$params);

                M\UserLoginRecords::commitTrans();
            } catch (\Exception $e) {
                M\UserLoginRecords::rollbackTrans();
                return $this->returnFail($e->getMessage());
            }
        }

        NOTHING:
        return $this->returnSuccess();
    }

    /**
     * [primePrecheck description]
     * @Author   FW
     * @DateTime 2024-04-09
     * @Email    123763712@qq.com
     * @param    [type]           $orderType 操作类型3-开通 4-升级 5-续费
     * @param    [type]           $levelId [description]
     * @return   [type]                    [description]
     */
    public function primePrecheck()
    {
        $orderType = (int)$this->request->post('orderType');
        $levelId = (int)$this->request->post('levelId');

        if ( !in_array($orderType , [3,4,5] ) ) return $this->returnFail('不允许的操作类型');

        $levelInfo = M\UserLevel::field("DATE_ADD(DATE(NOW()), INTERVAL days DAY) as expire_date,id,price,days,grade_type,rights_info,0 as order_type")->where('id',$levelId)->find();
        if ( empty($levelInfo) ) return $this->returnFail('等级不存在');

        $levelInfo->order_type = $orderType;

        ## 会员开通-直接把此等级的会员信息取出返回即可
        if ( $orderType == 3 ) goto FINAL_PROCESS;

        ## 会员升级-需要计算差价
        if ( $orderType == 4 ) {
            $levelInfo = M\UserLevel::field("DATE_ADD(DATE(NOW()), INTERVAL days DAY) as expire_date,id,price,days,grade_type,rights_info,4 as order_type")->where('grade_type','gt',$levelInfo->grade_type)->find();
            if ( empty($levelInfo) ) return $this->returnFail('无可用等级升级');

            $levelInfo->refundInfo = M\UserLevel::calcUserLevelRefund($this->uid);
            $levelInfo->price = bcsub($levelInfo->price,$levelInfo->refundInfo['leftAmt'],2);
        }

        ## 会员续费-需要
        if ( $orderType == 5 ) goto FINAL_PROCESS;

        FINAL_PROCESS:
        $levelInfo->grade_type_display = M\UserLevel::$grade_type[$levelInfo->grade_type]??'-';
        $levelInfo->expire_date_format = date('Y年m月d日',strtotime($levelInfo->expire_date));
        $levelInfo->price *= 1;
        return $this->returnSuccess($levelInfo);
    }

    /**
     * 重新拉取用户会员等级信息
     * （一般用于会员开通、升级、续费后刷新页面及更新本地缓存用）
     * @Author   FW
     * @DateTime 2024-04-10
     * @Email    123763712@qq.com
     * @return   [type]           [description]
     */
    public function resyncPrimeInfo()
    {
        $primeInfo = M\User::userPrimeInfo($this->uid);
        return $this->returnSuccess($primeInfo);
    }

    /**
     * 重新拉取用户信息
     * @Author   FW
     * @DateTime 2024-04-11
     * @Email    123763712@qq.com
     * @return   [type]           [description]
     */
    public function resyncUserInfo()
    {
        $user = M\User::alias('u')->field(M\User::LOGIN_FIELD)
        ->where('u.uid', $this->uid)
        ->find();

        $userInfo = [];
        if ( !empty($user) ) $userInfo = M\User::set_login($user);
        
        return $this->returnSuccess($userInfo);
    }

    /**
     * 用户领取的代金券记录列表
     * @Author   FW
     * @DateTime 2024-05-20
     * @Email    123763712@qq.com
     * @return   [type]           [description]
     */
    public function coupons()
    {
        $filter = $this->request->get();
        $filter['uid'] = $this->uid;
        $records = M\CouponRecords::getList($filter);
        
        return $this->returnSuccess($records['data']);
    }

    /**
     * 领取的代金券详情
     * @Author   FW
     * @DateTime 2024-05-20
     * @Email    123763712@qq.com
     * @param    [type]           $id [description]
     * @return   [type]               [description]
     */
    public function couponRecordDetails($id)
    {
        $record = M\CouponRecords::getOne($id);
        return $this->returnSuccess($record);
    }

    /**
     * 核销用户领取的代金券
     * @Author   FW
     * @DateTime 2024-05-20
     * @Email    123763712@qq.com
     * @return   [type]           [description]
     */
    public function couponRecordVerify()
    {
        $recordId = (int)input('id');
        $sales_admin_id = $this->model::calcSalesAdminId($this->uid);
        if ( !$sales_admin_id ) return $this->returnFail('您无权进行此项操作');

        try {
            $res = M\CouponRecords::verify($recordId);
            if ( $res === true ) return $this->returnSuccess();
        } catch ( \Exception $e ) {
            return $this->returnFail($e->getMessage());
        }

        return $this->returnFail('核销失败');
    }

    /**
     * 获取用户红点提示信息数量
     * @Author   FW
     * @DateTime 2024-05-21
     * @Email    123763712@qq.com
     * @return   [type]           [description]
     */
    public function redDotTipNums()
    {
        $nums = [
            'coupon' => 0,
            'message'=> 0
        ];

        // 用户优惠券数量
        $nums['coupon'] = M\CouponRecords::alias('m')
        ->join('__COUPON__ c','m.coupon_id = c.id')
        ->where('m.uid',$this->uid)->where('m.status' , M\CouponRecords::STATUS_UNUSE)
        ->count();

        // 用户未读消息数量
        $nums['message'] = M\Message::alias('m')
        ->where('m.uid',$this->uid)->where('m.read_time',0)
        ->count();
        return $this->returnSuccess($nums);
    }

    /**
     * 获取用户线路出行订单状态统计
     * @Author   FW
     * @DateTime 2024-05-21
     * @Email    123763712@qq.com
     * @return   [type]           [description]
     */
    public function orderStatic()
    {
        $status = M\OrderOuterRoutes::$status;

        $filter = '1=1';
        $uid  = (int)input('uid');
        $sales_admin = (int)input('sales_admin');
        if ( !$sales_admin ) {
            if ( $uid > 0 ) {
                $filter .= sprintf(" AND outer.id IN (SELECT order_outer_id FROM `eb_order` WHERE order_type = %d AND uid = %d)" , M\order::ORDER_TYPE_ROUTES , $uid);
            }
        }
        $data = [];
        foreach ( $status as $value => $text ) {
            $data[] = [
                'text'   => $text,
                'value'  => $value,
                'orders' => M\OrderOuterRoutes::alias('outer')->where('outer.status',$value)->where($filter)->count()
            ];
        }
        return $this->returnSuccess($data);
    }

    /**
     * 获取我的团队成员
     * @Author   FW
     * @DateTime 2024-05-21
     * @Email    123763712@qq.com
     * @return   [type]           [description]
     */
    public function teammembers()
    {
        $members = M\User::alias('m')->field("m.uid,m.avatar,m.mobile,m.full_name,m.nickname,m.status,DATE_FORMAT(m.register_date,'%y年%m月%d日') as register_date,m.level_id,m.gender,m.last_time,m.golds,m.remark,m.is_idcheck,m.birthday,m.tour_perfer,m.tour_target")
        ->where('m.spread_uid', $this->uid)
        ->select();

        return $this->returnSuccess($members);
    }

    /**
     * 消息列表
     * @Author   FW
     * @DateTime 2024-03-13
     * @Email    123763712@qq.com
     * @return   [type]           [description]
     */
    public function messages()
    {
        $filter = [
            'page' => $this->page,
            'uid'  => $this->uid,
        ];
        return $this->returnSuccess(M\Message::getList($filter)['data']);
    }
}//Class End